<template>
  <entity-view
    :operator-type="operatorType"
    :model="beanInfo"
    @submit="submitBank"
    :rules="rules"
    ref="form"
  >
    <div class="sub-content-flex">
      <form-item
        label="通道标识"
        v-model="beanInfo.dstChannelId"
        prop="dstChannelId"
        disabled
      ></form-item>
      <form-item
        label="支持业务类别"
        v-model="beanInfo.supportBizType"
        prop="supportBizType"
        inputType="select"
        :options="supportBizTypeList"
        @change="(value) => handleChange(value, 'supportBizType')"
      ></form-item>
      <form-item
        label="联行行号"
        v-model="beanInfo.bankNo"
        prop="bankNo"
        inputType="select"
        :options="bankNoList"
        :showSearch="true"
        optionsValue="bankBranchCode"
        optionsLabel="bankBranchName"
        @change="(value) => handleChange(value, 'bankNo')"
        @search="getBankCodeSelect2List"
      ></form-item>
      <form-item
        label="银行简码"
        v-model="beanInfo.bankSimpleCode"
        prop="bankSimpleCode"
      ></form-item>
      <form-item
        label="借记账户支持标识"
        v-model="beanInfo.debitSupportFlag"
        prop="debitSupportFlag"
        inputType="select"
        :options="debitSupportFlagList"
        @change="(value) => handleChange(value, 'debitSupportFlag')"
      ></form-item>
      <form-item
        label="贷记账户支持标志"
        v-model="beanInfo.creditSupportFlag"
        prop="creditSupportFlag"
        inputType="select"
        :options="creditSupportFlagList"
        @change="(value) => handleChange(value, 'creditSupportFlag')"
      ></form-item>
      <form-item
        label="参与营销活动标志"
        v-model="beanInfo.mcFlag"
        prop="mcFlag"
        inputType="select"
        :options="mcFlagList"
        @change="(value) => handleChange(value, 'mcFlag')"
      ></form-item>
      <form-item
        label="营销活动编号"
        v-model="beanInfo.mcNo"
        prop="mcNo"
      ></form-item>
      <form-item
        label="营销活动名称"
        v-model="beanInfo.mcName"
        prop="mcName"
      ></form-item>
      <form-item
        label="单笔交易限额(元)"
        v-model="beanInfo.singleLimitAmt"
        prop="singleLimitAmt"
      ></form-item>
      <form-item
        label="日累计交易限额(元)"
        v-model="beanInfo.dayLimitAmt"
        prop="dayLimitAmt"
      ></form-item>
      <form-item label="银行logo"  v-model="beanInfo.bankLogoUrl" prop="bankLogoUrl">
        <div class="clearfix">
          <a-upload
            :disabled="operatorType=='view'"
            list-type="picture-card"
            @preview="handlePreview"
            @change="handleChangeFile"
            :customRequest="handleUpload"
            :file-list="fileList"
          >
            <div v-if="fileList.length==0">
              <a-icon type="plus" />
              <div class="ant-upload-text">
                上传logo
              </div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </div>
      </form-item>
      <form-item
        label="其他信息"
        v-model="beanInfo.otherData"
        prop="otherData"
        inputType="textarea"
      ></form-item>
    </div>
  </entity-view>
</template>
<script>
import EntityView from "../../../../components/common/entityView/EntityView.vue";
import FormItem from "../../../../components/common/entityView/FormItem.vue";
import store from "../../../../store";
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

export default {
  name: "PBankOperation",
  inject: [ 'operationContext'],
  components: {
    EntityView,
    FormItem,
  },
  props: {
    query: Object,
  },
  data: function () {
    return {
      modalBankTitle: "",
      operatorType: "add",
      modalBankVisible: true,
      instId: "",
      beanInfo: {
        dstChannelId: "",
        dstChannelName: "",
        dstChannelType: "",
        dstChannelTypeDesc: "",
        channelNo: "",
        providerMchntNo: "",
        appId: "",
        subAppId: "",
        supportBizType: "",
      },
      rules: {
        dstChannelId: [{ required: true, message: "必输", trigger: "blur" }],
        supportBizType: [{ required: true, message: "必输", trigger: "blur" }],
        bankNo: [{ required: true, message: "必输", trigger: "blur" }],
        bankSimpleCode: [{ required: true, message: "必输", trigger: "blur" }],
        debitSupportFlag: [
          { required: true, message: "必输", trigger: "blur" },
        ],
        creditSupportFlag: [
          { required: true, message: "必输", trigger: "blur" },
        ],
        mcFlag: [{ required: true, message: "必输", trigger: "blur" }],
        bankLogoUrl: [{ required: true, message: "必输", trigger: "blur" }]
      },
      loading: false,
      pageInfo: {},
      supportBizTypeList: [
        { value: "00", name: "智能路由" },
        { value: "11", name: "企业网银业务" },
        { value: "20", name: "快捷支付业务" },
        { value: "10", name: "人个网银业务" },
      ],
      bankNoList: [],
      debitSupportFlagList: [
        { value: "Y", name: "支持" },
        { value: "N", name: "不支持" },
      ],
      creditSupportFlagList: [
        { value: "Y", name: "支持" },
        { value: "N", name: "不支持" },
      ],
      mcFlagList: [
        { value: "Y", name: "参与" },
        { value: "N", name: "不参与" },
      ],
      uploadLogoUrl: "",
      headers: {},
      uploading: false,
      previewVisible: false,
      previewImage: '',
      fileList: [],
      imgFile:[],
    };
  },
  mounted() {
    //初始化上传图片的参数
    this.headers["Authentication"] = store.state.account.token;
  },
  methods: {
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handleChangeFile({ fileList }) {
      this.fileList = fileList;
    },
    setOperatorType(type) {
      this.operatorType = type;
    },
    async submitBank() {
      let res;
      switch (this.operatorType) {
        case "add":
          res = await this.add();
          break;
        case "edit":
          res = await this.edit();
          break;
        case "view":
          res = true;
          break;
        default:
          break;
      }
      return res;
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    viewLicenceImg(e) {
      this.previewImage = this.beanInfo.bankLogoUrl;
      this.previewVisible = true;
      e.stopPropagation();
    },
    delLicenceImg(e) {
      this.$set(this.signInfo,'licenceImage',null)
      e.stopPropagation();
    },
    async getBankCodeSelect2List() {
      try {
        const res = await this.$get(
          "/admin/merParam/bankCodeInfo/bankCodeSelect2List",
          {
            q: "",
          }
        );
        if (res.status === 200) {
          this.bankNoList = res.data || [];

          return true;
        } else {
          this.$message.error(res.data.message);
          return false;
        }
      } catch (error) {
        console.log(error);
      }
    },
    async add() {
      const res = await this.$refs.form.validate();
      if (res) {
        const params = this.beanInfo;
        params["instId"] = this.instId;

        this.bankNoList.forEach(i => {
          if (i.bankBranchCode === params.bankNo && i.bankBranchLevel === "00")   {
            params.bankName = i.bankBranchName;
          }
        })
        const res = await this.$post(
          "/admin/igas/pBankSupportCfg/edit",
          params
        );
        if (res.status === 200) {
          this.$message.success("新增成功！");
          return true;
        } else {
          this.$message.error(res.data.message);
          return false;
        }
      }
    },
    async edit() {
      const res = await this.$refs.form.validate();
      if (res) {
        const params = this.beanInfo;
        params["optFlag"] = "upd";
        const res = await this.$post(
          "/admin/igas/pBankSupportCfg/edit",
          params
        );
        if (res.status === 200) {
          this.$message.success("保存成功！");
          return true;
        } else {
          this.$message.error(res.data.message);
          return false;
        }
      }
    },
    resetFields() {
      return this.$refs.form && this.$refs.form.resetFields();
    },
    async getBankLogoUrl(imageLocalPath){
      const params = {
        imageLocalPath: imageLocalPath,
        fileType: "08",
        instId: this.instId,
      };
      const res = await this.$get(
        "/admin/mcmp/bMchntImageInfo/getBompImg",params
      );
      if (res.data.code === "100000") {
        this.fileList = [{
          name: res.data.data.imageLocalPath,
          uid: new Date().getTime(),
          status: 'done',
          url: res.data.data.imageData,
        }]
        this.$set(this.beanInfo, 'bankLogoUrl', res.data.data.imageLocalPath);
        return true;
      } else {
        this.$message.error(res.data.message);
        return false;
      }
    },
    async setBeanInfo(beanInfo, instId) {
      console.log(instId);
      this.beanInfo = beanInfo;
      this.instId = instId;
      if(this.beanInfo.bankLogoUrl!=null) {
        await this.getBankLogoUrl(this.beanInfo.bankLogoUrl);
      }
      // this.uploadLogoUrl = `http://172.17.100.9:10126/upmp/admin/mcmp/bMchntImageInfo/uploadBomp?instId=${instId}&imageType=08`;
      // console.log("uploadLogoUrl", uploadLogoUrl);
      try {
        await this.getBankCodeSelect2List();
      } catch (error) {
        console.log(error);
      }
    },
    handleChange(value, param) {
      this.beanInfo[param] = value;
    },
    logoChange(info) {
      if (info.file.status === "uploading") {
        this.loading = true;
        return;
      }
      if (info.file.status === "done") {
        getBase64(info.file.originFileObj, (imageUrl) => {
          this.beanInfo.bankLogoUrl = imageUrl;
          this.loading = false;
        });
      }
    },
    handleRemove(file) {
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
    },
    // beforeUpload(file) {
    //   this.fileList = [...this.fileList, file];
    //   return false;
    // },
    async handleUpload(fileList) {
      console.log(arguments)
      const formData = new FormData();
      formData.append('imgFile', fileList.file);
      formData.append('imageType', "08");
      formData.append('instId', this.instId);
      // formData.append('mchntNo', this.beanInfo.mchntNo);
      try {
        const res = await this.$upload(
          "/admin/mcmp/bMchntImageInfo/uploadBomp",formData
        );
        if (res.data.code === "100000") {
          this.fileList = [{
            name: res.data.data.imageLocalPath,
            uid: new Date().getTime(),
            status: 'done',
            url: res.data.data.imageData,
          }]
          this.$set(this.beanInfo, 'bankLogoUrl', res.data.data.imageLocalPath);
          this.$message.success("上传成功！");
          return true;
        } else {
         this.$message.error(res.data.message);
          return false;
        }
      } catch (e) {
        this.handleRemove(this.fileList.file);
        console.log(e)
      }


    },
  }}
</script>

<style lang="less" scoped>
@import "../../../../../static/less/Common";

.subtitle {
  width: 100%;
  font-size: 18px;
  margin-bottom: 10px;
}
.sub-content-flex {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
}
.sub-content-block {
  display: block;
  flex-wrap: wrap;
  width: 100%;
}
</style>
